package com.utaedang.jesseclub;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.TextView;
import android.widget.Toast;

import com.utaedang.jesseclub.utils.DateUtil;
import com.utaedang.jesseclub.utils.GlobalContext;

public class Main extends Activity {
	// Used to communicate state changes in the DownloaderThread
	public static final int MESSAGE_GENERAL = 0000;
	public static final int MESSAGE_DOWNLOAD_STARTED = 1000;
	public static final int MESSAGE_DOWNLOAD_COMPLETE = 1001;
	public static final int MESSAGE_UPDATE_PROGRESS_BAR = 1002;
	public static final int MESSAGE_DOWNLOAD_CANCELED = 1003;
	public static final int MESSAGE_CONNECTING_STARTED = 1004;
	public static final int MESSAGE_ENCOUNTERED_ERROR = 1005;
	public static final int MESSAGE_FILEHANDLING_RUNNGING = 1006;
	public static final int MESSAGE_DOWNLOAD_YES = 1000;
	public static final int MESSAGE_DOWNLOAD_NO = 1001;
	
	// instance variables
	private Main thisActivity;
	private Thread downloaderThread;
	private ProgressDialog progressDialog;
	Handler handler;
	String verName = "1.0";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		// 파일 다운로드
		thisActivity = this;
		downloaderThread = null;
		progressDialog = null;

		// Version Info Check!
		PackageManager pm = getPackageManager();
		try {
			verName = pm.getPackageInfo(getPackageName(),
					PackageManager.GET_SIGNATURES).versionName;
		} catch (Exception e) {
		}
		TextView txtVersion = (TextView) findViewById(R.id.txtVersion);
		txtVersion.setText("v" + verName);

		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case MESSAGE_DOWNLOAD_STARTED:
					startActivity(new Intent(thisActivity, Downloader.class));// 이동될
					//Intent intent = new Intent(thisActivity, Downloader.class); 
					//thisActivity.startActivity(intent);
					break;
				case MESSAGE_DOWNLOAD_COMPLETE:
					startActivity(new Intent(thisActivity, JesseclubActivity.class));// 이동될
					finish();
					break;
				default:
					// nothing to do here
					break;
				}

			}
		};

		//파일 다운로드 필요 여부 확인
		if(GlobalContext.NEED_FILE_DOWNLOAD){
			try {
				File currentFile = new File(GlobalContext.DB_PATH
						+ "files/test01.zip");
				String htmlmsg = "";
				Message msg;
	
				if (!currentFile.exists()) {
					htmlmsg = "현재 설치된 DB가 없습니다.<br>";
					htmlmsg += thisActivity.getString(R.string.app_name)
							+ "를 사용하기 위해서 DB를 설치해야 합니다.<br>";
					htmlmsg += "지금 설치하시겠습니까?<br>";
					htmlmsg += "<font size='7'>※본 과정은 네트워크를 사용하므로 와이파이 환경에서 진행하시길 권장합니다.</font>";
	
					// 파일 다운로드 묻기
					downloadDialogHtmlView(htmlmsg);
				} else {
					URL url = new URL(GlobalContext.DB_URL);
					URLConnection conn = url.openConnection();
					if (conn.getContentLength() > 0) {
						if (currentFile.lastModified() < conn.getLastModified()) {
	
							Log.d("date", DateUtil
									.convTimestampToKoreanFullDate(currentFile
											.lastModified()));
							Log.d("date", DateUtil
									.convTimestampToKoreanFullDate(conn
											.getLastModified()));
	
							htmlmsg = "DB가 업데이트 되었습니다.<br><br>";
							htmlmsg += "현재 버전 : "
									+ DateUtil
											.convTimestampToKoreanFullDate(currentFile
													.lastModified()) + "<br>";
							htmlmsg += "최신 버전 : "
									+ DateUtil.convTimestampToKoreanFullDate(conn
											.getLastModified()) + "<br>";
							htmlmsg += "지금 업데이트 하시겠습니까?<br>";
							htmlmsg += "<font size='-1'>※본 과정은 네트워크를 사용하므로 와이파이 환경에서 진행하시길 권장합니다.</font>";
	
							// 파일 다운로드 묻기
							downloadDialogHtmlView(htmlmsg);
						}else{
							Toast.makeText(this, "버전 확인 완료", Toast.LENGTH_SHORT).show();
							//startActivity(new Intent(Main.this, DialogSample.class));// 이동
							handler.sendMessageDelayed(Message.obtain(handler, MESSAGE_DOWNLOAD_COMPLETE), 3000);
						}
					}
				}
	
			} catch (IOException e) {
				// TODO Auto-generated catch block
				Log.e("error", e.toString());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				Log.e("error", e.toString());
			} finally {
	
			}
		}else{
			Toast.makeText(this, "버전 확인 완료", Toast.LENGTH_SHORT).show();
			handler.sendMessageDelayed(Message.obtain(handler, MESSAGE_DOWNLOAD_COMPLETE), 3000);
		}

	}

	// back 버튼을 클릭시 종료 할건지에 대해 묻는다
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			String alertTitle = getResources().getString(R.string.app_name);
			String buttonMessage = getResources().getString(
					R.string.alert_msg_exit);
			String buttonYes = getResources().getString(R.string.button_yes);
			String buttonNo = getResources().getString(R.string.button_no);

			new AlertDialog.Builder(Main.this)
					.setTitle(alertTitle)
					.setMessage(buttonMessage)
					.setIcon(R.drawable.icon)
					.setPositiveButton(buttonYes,
							new DialogInterface.OnClickListener() {

								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									moveTaskToBack(true);
									finish();
								}
							}).setNegativeButton(buttonNo, null).show();
		}
		return true;
	}

	private void downloadDialogHtmlView(String msg) {
		AlertDialog.Builder ab = new AlertDialog.Builder(this);
		ab.setTitle("업데이트 설치");
	    ab.setIcon(R.drawable.icon);
		ab.setMessage(Html.fromHtml(msg));
		ab.setCancelable(false);
		ab.setPositiveButton(R.string.button_yes,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// Action for 'Yes' Button
						thisActivity.handler
								.sendEmptyMessage(MESSAGE_DOWNLOAD_YES);
					}
				});
		ab.setNegativeButton(R.string.button_no,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// Action for 'NO' Button
						dialog.cancel();
						thisActivity.handler
								.sendEmptyMessage(MESSAGE_DOWNLOAD_NO);
					}
				});
		ab.show();
	}

	@Override
	public void onNewIntent(final Intent newIntent) {
		super.onNewIntent(newIntent);

		boolean kill_app = newIntent.getBooleanExtra("KILL_APP", false);
		if (kill_app == true) {
			finish();
			requestKillProcess(this);
		}
	}

	public void requestKillProcess(final Context context) {

		int sdkVersion = Integer.parseInt(Build.VERSION.SDK);

		if (sdkVersion < 8) {
			ActivityManager am = (ActivityManager) context
					.getSystemService(Context.ACTIVITY_SERVICE);
			am.restartPackage(getPackageName());
		} else {
			new Thread(new Runnable() {
				public void run() {
					ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
					String name = getApplicationInfo().processName;

					while (true) {
						List<RunningAppProcessInfo> list = am
								.getRunningAppProcesses();

						for (RunningAppProcessInfo i : list) {
							if (i.processName.equals(name) == true) {

								if (i.importance >= RunningAppProcessInfo.IMPORTANCE_BACKGROUND)
									am.restartPackage(getPackageName());

								Thread.yield();
								break;
							}
						}
					}
				}

			}, "Process Killer").start();
		}
	}
	
	/**
	 * This is the Handler for this activity. It will receive messages from the
	 * DownloaderThread and make the necessary updates to the UI.
	 */
	public Handler activityHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			/*
			 * Handling MESSAGE_UPDATE_PROGRESS_BAR: 1. Get the current
			 * progress, as indicated in the arg1 field of the Message. 2.
			 * Update the progress bar.
			 */
			case MESSAGE_UPDATE_PROGRESS_BAR:
				if (progressDialog != null) {
					int currentProgress = msg.arg1;
					progressDialog.setProgress(currentProgress);
				}
				break;

			/*
			 * Handling MESSAGE_CONNECTING_STARTED: 1. Get the URL of the file
			 * being downloaded. This is stored in the obj field of the Message.
			 * 2. Create an indeterminate progress bar. 3. Set the message that
			 * should be sent if user cancels. 4. Show the progress bar.
			 */
			case MESSAGE_CONNECTING_STARTED:
				if (msg.obj != null && msg.obj instanceof String) {
					String url = (String) msg.obj;
					// truncate the url
					if (url.length() > 16) {
						String tUrl = url.substring(0, 15);
						tUrl += "...";
						url = tUrl;
					}
					String pdTitle = thisActivity
							.getString(R.string.progress_dialog_title_connecting);
					String pdMsg = thisActivity
							.getString(R.string.progress_dialog_message_prefix_connecting);
					// pdMsg += " " + url;

					dismissCurrentProgressDialog();
					progressDialog = new ProgressDialog(thisActivity);
					progressDialog.setTitle(pdTitle);
					progressDialog.setMessage(pdMsg);
					progressDialog
							.setProgressStyle(ProgressDialog.STYLE_SPINNER);
					progressDialog.setIndeterminate(true);
					// set the message to be sent when this dialog is canceled
					Message newMsg = Message.obtain(this,
							MESSAGE_DOWNLOAD_CANCELED);
					progressDialog.setCancelMessage(newMsg);
					progressDialog.show();
				}
				break;

			/*
			 * Handling MESSAGE_DOWNLOAD_STARTED: 1. Create a progress bar with
			 * specified max value and current value 0; assign it to
			 * progressDialog. The arg1 field will contain the max value. 2. Set
			 * the title and text for the progress bar. The obj field of the
			 * Message will contain a String that represents the name of the
			 * file being downloaded. 3. Set the message that should be sent if
			 * dialog is canceled. 4. Make the progress bar visible.
			 */
			case MESSAGE_DOWNLOAD_STARTED:
				// obj will contain a String representing the file name
				if (msg.obj != null && msg.obj instanceof String) {
					int maxValue = msg.arg1;
					String fileName = (String) msg.obj;
					String pdTitle = thisActivity
							.getString(R.string.progress_dialog_title_downloading);
					String pdMsg = thisActivity
							.getString(R.string.progress_dialog_message_prefix_downloading);
					pdMsg += " " + fileName;

					dismissCurrentProgressDialog();
					progressDialog = new ProgressDialog(thisActivity);
					progressDialog.setTitle(pdTitle);
					progressDialog.setMessage(pdMsg);
					progressDialog
							.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
					progressDialog.setProgress(0);
					progressDialog.setMax(maxValue);
					// set the message to be sent when this dialog is canceled
					Message newMsg = Message.obtain(this,
							MESSAGE_DOWNLOAD_CANCELED);
					progressDialog.setCancelMessage(newMsg);
					progressDialog.setCancelable(true);
					progressDialog.show();
				}
				break;

			/*
			 * Handling MESSAGE_DOWNLOAD_COMPLETE: 1. Remove the progress bar
			 * from the screen. 2. Display Toast that says download is complete.
			 */
			case MESSAGE_DOWNLOAD_COMPLETE:
				dismissCurrentProgressDialog();
				displayMessage(getString(R.string.user_message_download_complete));
				// finish();
				break;

			/*
			 * Handling MESSAGE_DOWNLOAD_CANCELLED: 1. Interrupt the downloader
			 * thread. 2. Remove the progress bar from the screen. 3. Display
			 * Toast that says download is complete.
			 */
			case MESSAGE_DOWNLOAD_CANCELED:
				if (downloaderThread != null) {
					downloaderThread.interrupt();
				}
				dismissCurrentProgressDialog();
				displayMessage(getString(R.string.user_message_download_canceled));
				thisActivity.handler.sendEmptyMessage(0);
				// finish();
				break;

			/*
			 * Handling MESSAGE_ENCOUNTERED_ERROR: 1. Check the obj field of the
			 * message for the actual error message that will be displayed to
			 * the user. 2. Remove any progress bars from the screen. 3. Display
			 * a Toast with the error message.
			 */
			case MESSAGE_ENCOUNTERED_ERROR:
				// obj will contain a string representing the error message
				if (msg.obj != null && msg.obj instanceof String) {
					String errorMessage = (String) msg.obj;
					dismissCurrentProgressDialog();
					displayMessage(errorMessage);
				}
				break;

			case MESSAGE_FILEHANDLING_RUNNGING:
				if (msg.obj != null && msg.obj instanceof String) {
					String pdTitle = thisActivity
							.getString(R.string.progress_dialog_message_filehandling);
					String pdMsg = thisActivity
							.getString(R.string.progress_dialog_message_prefix_filehandling);

					dismissCurrentProgressDialog();
					progressDialog = new ProgressDialog(thisActivity);
					progressDialog.setTitle(pdTitle);
					progressDialog.setMessage(pdMsg);
					progressDialog
							.setProgressStyle(ProgressDialog.STYLE_SPINNER);
					progressDialog.setIndeterminate(true);
					// set the message to be sent when this dialog is canceled
					Message newMsg = Message.obtain(this,
							MESSAGE_DOWNLOAD_CANCELED);
					progressDialog.setCancelMessage(newMsg);
					progressDialog.show();
				}
				break;
			case MESSAGE_GENERAL:
				// obj will contain a string representing the error message
				if (msg.obj != null && msg.obj instanceof String) {
					String errorMessage = (String) msg.obj;
					dismissCurrentProgressDialog();
					displayMessage(errorMessage);
				}
				break;
			default:
				// nothing to do here
				break;
			}
		}
	};

	/**
	 * If there is a progress dialog, dismiss it and set progressDialog to null.
	 */
	public void dismissCurrentProgressDialog() {
		if (progressDialog != null) {
			progressDialog.hide();
			progressDialog.dismiss();
			progressDialog = null;
		}
	}

	/**
	 * Displays a message to the user, in the form of a Toast.
	 * 
	 * @param message
	 *            Message to be displayed.
	 */
	public void displayMessage(String message) {
		if (message != null) {
			Toast.makeText(thisActivity, message, Toast.LENGTH_SHORT).show();
		}
	}

	public void onDestory() {
		super.onDestroy();
	}

}